package com.hx.vending.controller;

import com.hx.vending.annotation.Authorization;
import com.hx.vending.annotation.CurrentUserId;
import com.hx.vending.bean.config.AlipayConfig;
import com.hx.vending.bean.config.Constants;
import com.hx.vending.mqtt.RunnerSendMqtt;
import com.hx.vending.pay.WXPayUtil;
import com.hx.vending.service.IWXPayService;
import com.hx.vending.util.Constant;
import com.hx.vending.util.Msg;
import com.hx.vending.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by Administrator on 2018/12/3.
 * 微信支付
 */
@Controller
@RequestMapping("/wxpay")
public class WXPayController {

    @Autowired
    private IWXPayService iwxPayService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    /**
     * 支付后的返回方法
     * @param request
     * @return
     */
    @PostMapping(value="/WXNativeCallBack", produces="text/html;charset=UTF-8")
    @ResponseBody
    public String WXNativeCallBack(HttpServletRequest request){
        try {
            return this.iwxPayService.WXNativeCallBack(request);
        } catch (Exception e) {
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>";
        }
    }


    /**
     * 微信授权登陆(客户购买商品Android)
     * @return
     */
    @RequestMapping("/wxChatEmpower")
    public String wxChatEmpower(@RequestParam("onlineOrderId") String onlineOrderId){
        //appid 商户号   redirect_uri 重定向地址   state 自定义
        String requestURL=String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect", Constant.APPID, Constant.REDIRECT_URL, Constant.SCOPE_SNSAPI_USERINFO, onlineOrderId);
        return "redirect:"+requestURL;
    }

    /**
     * 微信授权登陆(客户购买商品web)
     * @return
     */
    @RequestMapping("/wxChatEmpowerWeb/{id}")
    public String wxChatEmpowerWeb(@PathVariable("id") String equipmentId, HttpServletRequest request){

        String userAgent = request.getHeader("user-agent");

        if (ToolUtil.isNotEmpty(userAgent) && userAgent.contains("AlipayClient")) {

            String redirect_uri = "http://star-hi.cn/vending/alipay/aliPayRedirectWeb";
            String url = String.format("https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=%s&scope=%s&redirect_uri=%s&state=%s",
                    AlipayConfig.APPID, "auth_user",redirect_uri,equipmentId);
            return "redirect:" + url;
        }else if (ToolUtil.isNotEmpty(userAgent) && userAgent.contains("MicroMessenger")) {
            //appid 商户号   redirect_uri 重定向地址   state 自定义
            String requestURL = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect", Constant.APPID, Constant.REDIRECT_WEB_URL, Constant.SCOPE_SNSAPI_USERINFO, equipmentId);
            return "redirect:" + requestURL;
        }
        return "";
    }


    /**
     * 微信授权登陆(商户提现)
     * @return
     */
    @RequestMapping("/wxCashChatEmpower")
    public String wxCashChatEmpower(HttpServletRequest request){

        String token = null;
        Cookie cookies[] = request.getCookies() ;
        Cookie c1 = null ;
        if(cookies != null){
            for(int i=0;i < cookies.length; i++){
                c1 = cookies[i] ;
                if (c1.getName().equals("token")) {
                    token = c1.getValue();
                }
            }
        }

        if (ToolUtil.isEmpty(token)) {
            return "未登录!!";
        }

        //appid 商户号   redirect_uri 重定向地址   state 自定义
        String requestURL=String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s&connect_redirect=1#wechat_redirect", Constant.APPID, Constant.REDIRECT_CASH_URL, Constant.SCOPE_SNSAPI_USERINFO, token);
        return "redirect:"+requestURL;
    }

    /**
     * 授权登陆重定向(客户购买商品Android)
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("/wxChatRedirect")
    public String wxChatRedirect(String code, String state){

        return this.iwxPayService.wxChatRedirect(code, state);
    }

    /**
     * 授权登陆重定向(客户购买商品web)
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("/wxChatRedirectWeb")
    public String wxChatRedirectWeb(String code, String state){

        return this.iwxPayService.wxChatRedirectWeb(code, state);
    }

    /**
     * 授权登陆重定向(商户提现)
     * @param code
     * @param state
     * @return
     */
    @RequestMapping("/wxChatCashRedirect")
    public String wxChatCashRedirect(String code, String state){

        return this.iwxPayService.wxChatCashRedirect(code, state);
    }


    /**
     * 微信提现到微信零钱
     * @return
     */
    @RequestMapping("/wxCashWithdrawal")
    @ResponseBody
    public Msg wxCashWithdrawal(Integer userId,Double money, @RequestParam(value = "withDrawalId", required = false)Integer withDrawalId){

        return this.iwxPayService.wxCashWithdrawal(userId, money, withDrawalId);
    }

    /**
     * 微信公众号预支付下单
     * @return
     */
    @RequestMapping("/wxJSAPIPay")
    @ResponseBody
    public Msg wxJSAPIPay(Integer customerId, Integer onlineOrderId){
        try {
            return this.iwxPayService.wxJSAPIPay(customerId, onlineOrderId);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail();
        }
    }


    /**
     * 判断跳转微信支付还是支付宝支付
     * @param request
     * @return
     */
    @RequestMapping("/paymentJump")
    public String paymentJump(HttpServletRequest request, @RequestParam("onlineOrderId") String onlineOrderId) {

        return this.iwxPayService.paymentJump(request, onlineOrderId);
    }

    /**
     * 判断是微信提现还是支付宝提现
     * @param userId      商户id
     * @param amount      提现金额
     * @param type        提现类型 0.微信提现到零钱 1.支付宝提现到零钱 2.微信提现到银行卡 3.支付宝提现到银行卡
     * @return
     */
    @RequestMapping("/cashWithDrawalJump")
    @ResponseBody
    @Authorization
    public Msg cashWithDrawalJump(@CurrentUserId Integer userId, Double amount, Integer type, @RequestParam(value = "withDrawalId", required = false)Integer withDrawalId) {

        return this.iwxPayService.cashWithDrawalJump(userId, amount, type, withDrawalId);
    }


    /**
     * 查询用户是否授权登陆
     * @param userId
     * @return
     */
    @RequestMapping("/selectUserOpenId")
    @ResponseBody
    @Authorization
    public Msg selectUserOpenId(@CurrentUserId Integer userId) {

        return this.iwxPayService.selectUserOpenId(userId);
    }


    /**
     * 查询商户提现信息
     * @param userId
     * @return
     */
    @RequestMapping("/selectUserWechatMessage")
    @ResponseBody
    @Authorization
    public Msg selectUserWechatMessage(@CurrentUserId Integer userId, @RequestParam(value = "type", required = false)Integer type) {

        return this.iwxPayService.selectUserWechatMessage(userId, type);
    }


    /**
     * 线下订单支付回调
     * @param underlineOrderId
     * @return
     */
    @RequestMapping("/UnderlinePayCallBack")
    @ResponseBody
    public Msg UnderlinePayCallBack(Integer underlineOrderId) {
        return this.iwxPayService.UnderlinePayCallBack(underlineOrderId);
    }



    ////////////////////////////////////////////////////其他测试使用/////////////////////////////////////////////////////////////////
    @RequestMapping("/tiaozhuan")
    public String tiaozhuan(){
        return "redirect:/index.jsp";
    }
    /**
     * 测试使用，微信扫码支付
     * @return
     */
    @RequestMapping("/ceshiceshi")
    @ResponseBody
    public String ceshiceshi(){

        //32位随机字符串
        String nonceStr = WXPayUtil.generateNonceStr(32);
        //map集合放值
        SortedMap<String,String> data=new TreeMap<String,String>();

        //公众账号ID    appid
        data.put("appid", Constant.APPID);
        //商户号        mch_id
        data.put("mch_id", Constant.WX_MCH_ID);
        //设备号 	   device_info
        data.put("device_info", "WEB");
        //随机字符串 	   nonce_str
        data.put("nonce_str", nonceStr);
        //商品描述 	   body
        data.put("body", "信可网络-微信扫码支付");
        //商户订单号 	   out_trade_no
        data.put("out_trade_no", nonceStr);
        //标价币种 	   fee_type
        data.put("fee_type", Constant.FEE_TYPE);
        //标价金额 	   total_fee
        data.put("total_fee", "1");
        //通知地址 	   notify_url
        data.put("notify_url", Constant.NOTIFY_URL);
        //交易类型 	   trade_type
        data.put("trade_type", Constant.TRADE_TYPE_NATIVE);
        //商品ID 	   product_id
        data.put("product_id", nonceStr);
        //自定义数据  (线上订单id+设备id+出货信息)
        data.put("attach", "attch");

        Map<String, String> resultMap = null;
        //生成签名
        String sign = null;
        try {
            sign = WXPayUtil.generateSignature(data, Constant.KEY, Constants.SignType.MD5);
            System.out.println("生成签名");
            System.out.println(sign);
            //发送给微信的xml
            String outputxml = WXPayUtil.mapToXml(data,sign);
            System.out.println("生成xml");
            System.out.println(outputxml);
            //发送xml获取返回结果

            String result = WXPayUtil.requestOnce(Constant.ORDERURL, nonceStr, outputxml, 6000, 8000, false, null);

            if (ToolUtil.isNotEmpty(result)) {
                System.out.println("返回值");
                System.out.println(result);
                //将返回的xml转换为map
                resultMap = WXPayUtil.xmlToMap(result);
                System.out.println("返回的code_url:"+resultMap.get("code_url"));

                return resultMap.get("code_url");
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/aaaa")
    public String aaaa(){

        //发送MQTT消息
        RunnerSendMqtt runnerSendMqtt = new RunnerSendMqtt();
        runnerSendMqtt.setMessage("666666666666666" + "," + "0301,1");
        runnerSendMqtt.setRedisTemplate(redisTemplate);
        runnerSendMqtt.setTheme("Delivery");
        runnerSendMqtt.setThreadName("出货指令");
        runnerSendMqtt.setRedisKey("DeliveryReceive-" + "666666666666666");
        runnerSendMqtt.setOnlineOrderId(187);
        runnerSendMqtt.start();

        return "ceshiceshiceshiceshicsshiceshiceshiceshiceshi";
    }


}
